package org.pet.controller;

import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.pet.entity.User;
import org.pet.entity.UserVo;
import org.pet.entity.wxlogin.LoginRequest;
import org.pet.service.UserService;
import org.pet.util.Result;
import org.pet.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 微信登录
     *
     * @param loginRequest code
     * @return
     */
    @PostMapping("wxLogin")
    public Result wxLogin(@RequestBody @Validated LoginRequest loginRequest) {
        return userService.wxLogin(loginRequest);
    }

    /**
     * 登录
     *
     * @param name
     * @return
     */
    @PostMapping("/login")
    public Result login( String name, @RequestParam @Pattern(regexp = "^\\S{8,16}$") String password) {
        return userService.login(name, password);
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody @Validated User user) {

        return userService.add(user);
    }

    /**
     * 显示用户信息
     * UserVo为处理后的User对象
     */
    @GetMapping("/userInfo")
    public Result<UserVo> userInfo() {

        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        UserVo userVo = userService.getUserById(id);
        return Result.success(userVo);
    }

    /**
     * 更新基本信息(昵称、生日、邮箱、性别、图片）
     *
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {

        return userService.update(user);
    }

    /**
     * 更新密码
     *
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 1为成功，0为失败
     */
    @PutMapping("/updatePwd")
    public Result updatePwd(@Pattern(regexp = "^\\S{8,16}$") String oldPassword,
                            @Pattern(regexp = "^\\S{8,16}$") String newPassword) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        return userService.updatePwd(id, oldPassword, newPassword);
    }

    /**
     * 删除
     *
     * @return
     */
    @DeleteMapping("/delete")
    public Result delete(@RequestParam Integer id) {

        return userService.delete(id);
    }
}
